package com.lagou.rpc.client;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import com.lagou.rpc.zk.ZkClient;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class DemoApplicaiton {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplicaiton.class, args);
    }

    @RestController
    class TestController {
        @Autowired
        private ZkClient zkClient;

        @RequestMapping("/info")
        public JSONObject dataSource() {
            DruidDataSource ds = ThreadDataSource.get();
            return new JSONObject().fluentPut("url", ds.getUrl())
                    .fluentPut("username", ds.getUsername());
        }

        /**
         * 刷新数据库信息
         * http://127.0.0.1:81/refresh?file=application-dev
         * @param file
         * @return
         * @throws Exception
         */
        @RequestMapping("/refresh")
        public int refresh(String file) throws Exception {
            ClassPathResource resource = new ClassPathResource(file + ".properties");
            String path = "/spring/datasource/application.cfg";
            if (zkClient.exists(path)) {
                zkClient.delete(path);
            }
            zkClient.create(path, IOUtils.toString(resource.getInputStream()), true);
            return 1;
        }
    }
}
